// Auto-register fonts under this directory using @font-face at runtime
// Supports: woff2, woff, ttf, otf

type SourceMap = Partial<Record<'woff2' | 'woff' | 'ttf' | 'otf', string>>;

const modules = import.meta.glob('./**/*.{woff2,woff,ttf,otf}', {
  eager: true,
  import: 'default'
}) as Record<string, string>;

const groups = new Map<
  string,
  {
    key: string;
    files: SourceMap;
  }
>();

for (const [path, url] of Object.entries(modules)) {
  const file = path.split('/').pop() || '';
  const [base, extRaw] = file.split('.');
  const ext = (extRaw || '').toLowerCase() as keyof SourceMap;
  if (!base || !ext) continue;
  const dir = path
    .split('/')
    .slice(0, -1)
    .join('/');
  const key = `${dir}/${base}`;
  const group = groups.get(key) || { key, files: {} };
  group.files[ext] = url;
  groups.set(key, group);
}

function parseName(baseName: string): { family: string; weight: number; style: 'normal' | 'italic' | 'oblique' } {
  const WEIGHT_MAP: Record<string, number> = {
    thin: 100,
    extralight: 200,
    ultralight: 200,
    light: 300,
    regular: 400,
    normal: 400,
    book: 400,
    medium: 500,
    semibold: 600,
    demibold: 600,
    bold: 700,
    extrabold: 800,
    heavy: 800,
    black: 900
  };

  const parts = baseName.split('-');
  let weight = 400;
  let style: 'normal' | 'italic' | 'oblique' = 'normal';
  const tail: string[] = [];

  for (let i = 1; i < parts.length; i++) {
    const token = parts[i].replace(/\s+/g, '').toLowerCase();
    if (token in WEIGHT_MAP) {
      weight = WEIGHT_MAP[token];
      continue;
    }
    if (token === 'italic' || token === 'oblique') {
      style = token as 'italic' | 'oblique';
      continue;
    }
    tail.push(parts[i]);
  }

  const familyRaw = [parts[0], ...tail].join(' ');
  const family = familyRaw.replace(/_/g, ' ');
  return { family, weight, style };
}

function buildCss(): string {
  let css = '';
  for (const { key, files } of groups.values()) {
    const baseName = key.split('/').pop() || key;
    const { family, weight, style } = parseName(baseName);
    const src: string[] = [];
    if (files.woff2) src.push(`url('${files.woff2}') format('woff2')`);
    if (files.woff) src.push(`url('${files.woff}') format('woff')`);
    if (files.ttf) src.push(`url('${files.ttf}') format('truetype')`);
    if (files.otf) src.push(`url('${files.otf}') format('opentype')`);
    if (!src.length) continue;
    css += `@font-face{font-family:'${family}';src:${src.join(',')};font-weight:${weight};font-style:${style};font-display:swap;}`;
  }
  return css;
}

const css = buildCss();
if (css) {
  const id = 'dynamic-fonts';
  let style = document.getElementById(id) as HTMLStyleElement | null;
  if (!style) {
    style = document.createElement('style');
    style.id = id;
    document.head.appendChild(style);
  }
  style.textContent = css;
}

